package com.yuanlrc.base.util;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtil {

    // 邮件服务器主机名
    private static final String HOST = "smtp.163.com";
    // 发件人邮箱用户名
    private static final String USERNAME = "caowey@163.com";
    // 发件人邮箱密码(或授权码)
    private static final String PASSWORD = "Best51898";
    // 发件人邮箱
    private static final String FROM = "caowey@163.com";
    // 邮件主题
    private static final String SUBJECT = "泰玄聊天系统验证码";

    /**
     * 发送邮件验证码
     * @param toEmail 收件人邮箱
     * @param verifyCode 验证码
     * @throws MessagingException
     */
    public static void sendEmailVerifyCode(String toEmail, String verifyCode) throws MessagingException {
        // 配置邮件服务器属性
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.auth", "true");
        props.put("mail.user", USERNAME);
        props.put("mail.password", PASSWORD);

        // 创建邮件会话
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        };

        Session session = Session.getDefaultInstance(props, authenticator);

        // 创建邮件消息
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(SUBJECT);
        message.setText("您的验证码是: " + verifyCode + ",请尽快完成验证。");

        // 发送邮件
        Transport.send(message);
    }
}
